import fs from 'fs';
import xlsx from 'node-xlsx';
import path from 'path';
import { BASE_DIST } from '../../constant';

const nodeExcel = require('excel-export');

/**
 * 读取Excel
 */
export const readExcel = (path: string, sheet = 0) => {
  let roughData = xlsx.parse(path);
  const data = roughData[sheet]['data'];
  let exportData = [];
  for (let rowId in data) {
    let row = data[rowId];
    exportData.push(row);
  }
  console.log(exportData, 'exportData');
  return exportData;
};

/**
 * 导出Excel
 */
export class ExportExcel {
  conf: Record<string, any> = {};

  constructor(name: string, cols: { caption: string, type: string }[]) {
    this.conf.name = name;
    this.conf.cols = cols;
  }

  addRow(data: any[][]) {
    this.conf.rows = [
      ...(this.conf.rows || []),
      ...data,
    ];
  }

  export(path: string) {
    const result = nodeExcel.execute(this.conf);
    fs.writeFile(path, result, 'binary', (err) => {
      err ? console.log(err) : null;
    });
  }
}

/**
 * demo
 */
const exportData = readExcel(path.resolve(__dirname, './test.xlsx'));
const exportIns = new ExportExcel('sheet', [
  {
    caption: '列名',
    type: 'string',
  }, {
    caption: '列名2',
    type: 'string',
  }]);
exportIns.addRow(exportData);
exportIns.export(path.join(BASE_DIST, 'OKK.xlsx'));
